package com.itheima.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器:1.定义拦截器 2.注册拦截器
@Slf4j
@Component
public class CheckInterceptor implements HandlerInterceptor {

    @Override //Controller方法执行前执行,返回true放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle....");
        /*用注册器筛选
        //获取路径
        String requestURI = request.getRequestURI();
        //判断是否为login请求*/

        //1.获取请求头
        String jwt = request.getHeader("token");
        //2.判断jwt是否存在
        if (!StringUtils.hasLength(jwt)){
            log.info("令牌不存在:{}",jwt);
            Result error = Result.error("no jwt");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return  false;
        }
        //3.jwt存在,解析令牌
        try{
            JwtUtils.jwtParse(jwt);
        }catch (Exception e){
            log.info("令牌错误");
            Result error = Result.error("jwt error");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return  false;
        }
        //4.放行
        log.info("准备放行");
        return true;
    }

    @Override   //Controller方法执行后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle....");
    }

    @Override   //渲染后执行,最后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion....");
    }
}
